/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.framework.pm;

import com.jb.framework.DuplicateComponentException;
import com.jb.framework.Persistable;
import com.jb.web.bean.Page;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;


public class JarPersistentManager extends XMLPersistentManager {
    private Log log = LogFactory.getLog(getClass().getName());

    public JarPersistentManager() {
    }

    public boolean isReadOnly() {
        return true;
    }

    public void create(Persistable root) throws DuplicateComponentException {
        //can not save
    }

    public void delete(Persistable root) {
        //can not detele
    }

    public boolean load(Persistable root) {
        if (!checkSecurity(root, READ)) {
            return false;
        }

        boolean loaded = false;
        String classPath = root.getClass().getName();
        classPath = classPath.replace('.', '/');

        String fileName = classPath + "/" + getFileName(root);

        if (!fileName.endsWith(EXT)) {
            fileName += EXT;
        }

        loaded = load(root, fileName);

        if (!loaded) {
            if (mParentPersistentManager != null) {
                loaded = mParentPersistentManager.load(root);
            }
        } else {
            if (root instanceof Page) {
                ((Page) root).setLoader(this);
                ((Page) root).setDesignable(false);
            }

            cache.put(location + root.getClass().getName() + root.getId(), root);
        }

        return loaded;
    }

    public void save(Persistable root, boolean saveChildren) {
        //can not save
    }

    public void save(Persistable obj) {
        //can not save
    }

    protected boolean load(Object root, String fileName) {
        try {
            // Step 1: create a DocumentBuilderFactory and configure it
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            // Set namespaceAware to true to get a DOM Level 2 tree with nodes
            // containing namesapce information.  This is necessary because the
            // default value from JAXP 1.0 was defined to be false.
            dbf.setNamespaceAware(true);

            // Set the validation mode to either: no validation, DTD
            // validation, or XSD validation
            dbf.setValidating(false);

            // Step 2: create a DocumentBuilder that satisfies the constraints
            // specified by the DocumentBuilderFactory
            DocumentBuilder db = dbf.newDocumentBuilder();

            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);

            if (inputStream == null) {
                return false;
            }

            /*
             String charset = "UTF-8";
             FileInputStream inputFile = new FileInputStream(fileName);
             InputStreamReader inputStream = new InputStreamReader(inputFile, charset);
             BufferedReader bufferReader = new BufferedReader(inputStream);
             */

            // Step 3: parse the input file
            Document doc = db.parse(inputStream);

            Node xmlElement = doc.getDocumentElement();

            processComponent((Persistable) root, xmlElement, false);
        } catch (Exception e) {
            if (log.isFatalEnabled()) {
                log.fatal(this, e);
            }
        }

        return true;
    }
}
